import json

from bson.objectid import ObjectId

from api_base import *


class APIMassageHandler(APIBaseHandler):
    @check_role(RoleStudent)
    async def get(self):
        '''
        获取消息
        '''
        skip = 0
        limit = 0
        try:
            skip = int(self.get_argument('skip'))
            limit = int(self.get_argument('limit'))
        except:
            pass
        massages = []
        async for item in self.db.massages.find({'to': self.current_user}).sort([('time', -1)]).limit(limit).skip(skip):
            item['_id'] = str(item['_id'])
            massages.append(item)
        self.write_json(massages)

    @check_role(RoleStudent)
    async def post(self):
        '''
        消息操作
        '''
        try:
            js = json.loads(self.request.body)
            op = js['op']
            massageids = js['massageids']
        except:
            self.write_json({'info': 'json_error'})
            return
        if op == 'del':
            res = await self.db.massages.delete_many({
                '_id': {'$in': [ObjectId(massageid) for massageid in massageids]},
                'to': self.current_user
            })
            self.write_json({'info': 'ok',
                             'deleted': res.deleted_count})
        elif op == 'read':
            res = await self.db.massages.update_many({
                '_id': {'$in': [ObjectId(massageid) for massageid in massageids]},
                'to': self.current_user
            }, {
                '$set': {'read': True}
            })
            self.write_json({'info': 'ok',
                             'matched': res.matched_count,
                             'modified': res.modified_count})
        else:
            self.write_json({'info': 'unkonwn op'})
